package com.vlin.controller.token;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.session.Session;
import org.springframework.session.SessionRepository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.vlin.errorcode.ErrorCode;
import com.vlin.service.user.LoginService;
import com.vlin.util.app.result.ResultUtils;

@RestController
public class TokenController {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@SuppressWarnings("rawtypes")
	@Autowired
	private SessionRepository sessionRepository;
	
	@Autowired
	private LoginService loginService;
	

	@SuppressWarnings("unchecked")
	@RequestMapping("token")
	public String login(String username, String password) {

		Session s = sessionRepository.createSession();
		s.setAttribute("Login", false);
		sessionRepository.save(s);
		String sessionId = loginService.userLogin(username, password, s.getId());
		logger.info("Get sessionId is {}", sessionId);
		Session ssion = sessionRepository.findById(sessionId);
		if (ssion != null && ssion.getAttribute("User") != null) {
			JSONObject result = new JSONObject();
			result.put("sessionId", sessionId);
			return ResultUtils.result(result);
		}
		
		return ResultUtils.result(ErrorCode.USER_NOT_EXIST);
	}
	
}
